from machine import I2C
import utime

# I2C地址
HDC1080_ADDRESS = (0x40)    # 1000000

# 寄存器
HDC1080_TEMPERATURE_REGISTER = (0x00)
HDC1080_HUMIDITY_REGISTER = (0x01)
HDC1080_CONFIGURATION_REGISTER = (0x02)
HDC1080_MANUFACTURERID_REGISTER = (0xFE)
HDC1080_DEVICEID_REGISTER = (0xFF)
HDC1080_SERIALIDHIGH_REGISTER = (0xFB)
HDC1080_SERIALIDMID_REGISTER = (0xFC)
HDC1080_SERIALIDBOTTOM_REGISTER = (0xFD)


# 配置寄存器
HDC1080_CONFIG_RESET_BIT = (0x8000)
HDC1080_CONFIG_HEATER_ENABLE = (0x2000)
HDC1080_CONFIG_ACQUISITION_MODE = (0x1000)
HDC1080_CONFIG_BATTERY_STATUS = (0x0800)
HDC1080_CONFIG_TEMPERATURE_RESOLUTION = (0x0400)
HDC1080_CONFIG_HUMIDITY_RESOLUTION_HBIT = (0x0200)
HDC1080_CONFIG_HUMIDITY_RESOLUTION_LBIT = (0x0100)

HDC1080_CONFIG_TEMPERATURE_RESOLUTION_14BIT = (0x0000)
HDC1080_CONFIG_TEMPERATURE_RESOLUTION_11BIT = (0x0400)

HDC1080_CONFIG_HUMIDITY_RESOLUTION_14BIT = (0x0000)
HDC1080_CONFIG_HUMIDITY_RESOLUTION_11BIT = (0x0100)
HDC1080_CONFIG_HUMIDITY_RESOLUTION_8BIT = (0x0200)

I2C_SLAVE = 0x0703


class HDC1080:

    def __init__(self, i2c):

        self.i2c = i2c
        utime.sleep_ms(20)

        self.i2c.write(64, b'\x02\x10\x00')
        # self.i2c.writeto_mem(64, 0x02, bytes([0x10, 0x00]))

        utime.sleep_ms(20)


    def readTemperature(self):

        self.i2c.write(64, b'\x00')

        utime.sleep_ms(50)

        data = self.i2c.read(64, 2)  # 读2字节温度数据

        buf = bytesToInt2(data)  #将数据字节转整型

        # 转换数据
        cTemp = (buf / 65536.0) * 165.0 - 40

        return cTemp

    def readHumidity(self):
            
        self.i2c.write(64, b'\x01')

        utime.sleep_ms(50)


        data = self.i2c.read(64, 2)  # 读2字节湿度数据

        buf = bytesToInt2(data)

        # 转换数据
        humidity = (buf / 65536.0) * 100.0

        return humidity


#字节转整型函数
def bytesToInt2(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
    return result
